/**
 * Anderground project - Subway maps processor application.
 * Copyright (C) 2008-2009 Eldar Abusalimov, Ilya Shurigyn
 * 
 * This file is part of Anderground.
 * 
 * Anderground is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Anderground is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Anderground.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.anderground.modules.storage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


/**
 * Uses {@link OutputStream} as a destination to write the data to.
 * 
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 * @param <T>
 *            data type
 */
public abstract class AbstractStreamWriter<T> extends
		AbstractWriter<T, OutputStream> {

	private final File file;
	private OutputStream outputStream;
	private final boolean closeAfterRead;

	/**
	 * Constructs a new {@link AbstractStreamWriter} that uses the specified
	 * {@link File} for the future reading.
	 * 
	 * @param file
	 *            the file to write a data to
	 */
	public AbstractStreamWriter(File file) {
		if (file == null) {
			throw new IllegalArgumentException("file cannot be null");
		}
		this.file = file;
		closeAfterRead = true;
	}

	/**
	 * Constructs a new {@link AbstractStreamWriter} that uses a {@link File}
	 * created by converting the specified path string.
	 * 
	 * @param path
	 *            the path of a file to write a data to
	 */
	public AbstractStreamWriter(String path) {
		this(new File(path));
	}

	/**
	 * Constructs a new {@link AbstractStreamWriter} that uses the specified
	 * {@link OutputStream} for the future writing.
	 * 
	 * @param outputStream
	 *            the stream to write a data to
	 * @param closeAfterRead
	 *            defines whether to close the stream after
	 *            {@link #write(Object)} completes
	 */
	public AbstractStreamWriter(OutputStream outputStream,
			boolean closeAfterRead) {
		if (outputStream == null) {
			throw new IllegalArgumentException("outputStream cannot be null");
		}
		this.outputStream = outputStream;
		this.closeAfterRead = closeAfterRead;
		file = null;
	}

	@Override
	public final void closeIO(OutputStream io) throws IOException {
		io.close();
	}

	@Override
	public final OutputStream openIO() throws IOException {
		if (file != null) {
			outputStream = new FileOutputStream(file);
		}
		return outputStream;
	}

	@Override
	public final boolean shouldCloseIOAfterComplete() {
		return closeAfterRead;
	}

}
